<template>
  <div class="data-results">
    <div class="table-container">
      <div class="table-header">
        <span class="table-title">项目基本信息</span>
      </div>
      <el-descriptions :column="1" border class="custom-descriptions">
        <el-descriptions-item label="项目名称">{{ purposeScopeData?.projectName || "未知项目" }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ purposeScopeData?.productName || "未知产品" }}</el-descriptions-item>
        <el-descriptions-item label="项目目的">{{ purposeScopeData?.purpose || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="系统边界">{{ purposeScopeData?.systemBoundary || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="功能单位">{{ purposeScopeData?.functionalUnit || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="核算依据">{{ purposeScopeData?.accountingBasis || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="核算方法">{{ purposeScopeData?.accountingMethod || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="数据取舍原则">{{ purposeScopeData?.dataPrinciple || "未设定" }}</el-descriptions-item>
        <el-descriptions-item label="数据质量要求">{{ purposeScopeData?.dataQuality || "未设定" }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">外购材料碳排放分析</span>
      </div>
      <div ref="echarts1Ref" class="echarts"></div>
      <div class="description-container" style="margin-top: 20px">
        <p>
          <span>某些材料的PCF值相对较高，需要引起注意。具体来说，</span>
          <span>{{ highPCFMaterialName }}</span>
          <span>的PCF值为</span>
          <span>{{ highPCFValue }}</span>
          <span>kgCO₂eq，显著高于其他材料。</span>
        </p>
      </div>
    </div>
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">内部工序与外部材料PCF比较</span>
      </div>
      <div ref="echarts2Ref" class="echarts"></div>
      <div class="description-container" style="margin-top: 20px">
        <p>
          <span>{{ comparePCF }}</span>
        </p>
      </div>
    </div>
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">单元过程碳排放值</span>
      </div>
      <div ref="echarts3Ref" class="echarts"></div>
      <div class="description-container" style="margin-top: 20px">
        <p>
          <span>单元过程中碳排放值较高的工序需要重点关注。其中，</span>
          <span>{{ highPCFProcessName }}</span>
          <span>的PCF值为</span>
          <span>{{ highPCFProcessValue }}</span>
          <span>kgCO₂eq，是碳排放量最大的单元过程。</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="useProtable">
import { ref, onMounted, computed, nextTick } from "vue";
import * as echarts from "echarts";
import { useEcharts } from "@/hooks/useEcharts";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";

const route = useRoute();
const echarts1Ref = ref<HTMLElement>();
const echarts2Ref = ref<HTMLElement>();
const echarts3Ref = ref<HTMLElement>();
const purposeScopeData = ref();
const PCFs_outMaterial = ref();
const processTotal = ref<number>(0);
const eachProcessPCF = ref<{ name: string; value: number }[]>([]);

// 挂载函数
onMounted(async () => {
  // 初始化项目
  await initFormData();
  await fetchTotalPCF();
  await nextTick();
  initChart_outMaterial();
  initChart_inAndOut();
  initChart_Process();
});

const initFormData = async () => {
  const projectId = route.params.projectId as string;
  //数据库
  const response = await axios.get(baseUrl + "/api/carbon/getPurposeScopeDataById?projectId=" + projectId);
  if (response) {
    purposeScopeData.value = response.data.data;
  }
  try {
    //数据库
    const response = await axios.get(baseUrl + "/api/carbon/getOutMaterialPCF?projectId=" + projectId);
    if (response.data && response.data.code === 200) {
      PCFs_outMaterial.value = response.data.data;
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取外购材料PCF失败";
      console.error("获取外购材料PCF错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取外购材料PCF出错:", error);
    ElMessage.error("获取外购材料PCF失败，可能是因为参数错误或网络问题");
  }
};

const fetchTotalPCF = async () => {
  const projectId = route.params.projectId?.toString();
  if (!projectId) return;

  try {
    const response = await axios.post(`${baseUrl}/api/carbon/CalculateTotalPCF`, {
      projectId: Number(projectId)
    });

    if (response.data.code !== 200) {
      throw new Error(response.data.msg || "获取总碳足迹失败");
    }

    const data = response.data.data;
    processTotal.value = data.processTotal || 0;
    eachProcessPCF.value = Array.isArray(data.eachProcessPCF) ? data.eachProcessPCF : [];

    // 获取到数据后重新渲染内外比例图
    window.requestAnimationFrame(() => {
      initChart_outMaterial();
      initChart_inAndOut();
      initChart_Process();
    });
  } catch (error) {
    console.error("获取总碳足迹失败:", error);
    ElMessage.error("获取总碳足迹失败");
  }
};

const baseUrl = import.meta.env.VITE_BASE_URL;

// 监听路由参数变化
// watch(
//   () => route.params.projectId,
//   async () => {
//     await getBlockchainInfo(); // 当项目ID变化时重新获取区块链信息
//   }
// );

// 计算PCF最高的材料名称
const highPCFMaterial = computed(() => {
  if (!Array.isArray(PCFs_outMaterial.value) || PCFs_outMaterial.value.length === 0) return { materialName: "未知", PCF: 0 };
  return PCFs_outMaterial.value.reduce(
    (max: any, current: any) => (current.PCF > max.PCF ? current : max),
    PCFs_outMaterial.value[0]
  );
});

// 提取高PCF的材料名称和数值
const highPCFMaterialName = computed(() => highPCFMaterial.value.materialName);
const highPCFValue = computed(() => highPCFMaterial.value.PCF);

// 计算所有外购材料PCF的总和
const totalPCFValue = computed(() => {
  if (!Array.isArray(PCFs_outMaterial.value)) return 0;
  return PCFs_outMaterial.value.reduce((sum: any, current: any) => sum + current.PCF, 0);
});

// 计算所有内部流程PCF的总和
const totalProcessValue = computed(() => {
  return eachProcessPCF.value.reduce((sum: any, current: any) => sum + current.value, 0);
});

// 修改计算PCF最高的单元过程，使用合并后的数据
const highPCFProcess = computed(() => {
  if (!eachProcessPCF.value || eachProcessPCF.value.length === 0) {
    return { name: "未知", value: 0 };
  }
  return eachProcessPCF.value.reduce((max, current) => (current.value > max.value ? current : max), eachProcessPCF.value[0]);
});

// 提取高PCF的过程名称和数值
const highPCFProcessName = computed(() => highPCFProcess.value.name || "未知过程");
const highPCFProcessValue = computed(() => highPCFProcess.value.value || 0);

/**内部工序与外部材料PCF比较 */
const comparePCF = computed(() => {
  if (totalPCFValue.value > totalProcessValue.value) {
    return "外购材料的碳排放更大";
  } else if (totalPCFValue.value < totalProcessValue.value) {
    return "内部工序的碳排放更大";
  } else {
    return "外购材料和内部工序的碳排放相等";
  }
});

/**初始化图表_外购材料 */
const initChart_outMaterial = () => {
  if (!echarts1Ref.value) return;
  const myChart = echarts.init(echarts1Ref.value);
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "10%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: PCFs_outMaterial.value.map((item:any) => item.materialName),
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: "value",
      name: "kgCO2eq",
      nameLocation: "middle",
      nameGap: 40
    },
    series: [
      {
        type: "bar",
        barWidth: "45px",
        data: PCFs_outMaterial.value.map((item:any) => item.PCF),
        itemStyle: {
          color: "#C5D8FF",
          borderRadius: [12, 12, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: "#6B9DFE"
          }
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c} kgCO2eq"
        }
      }
    ]
  };
  useEcharts(myChart, option);
};

/**初始化图表_外购材料 */
const initChart_inAndOut = () => {
  if (!echarts2Ref.value) return;
  const myChart = echarts.init(echarts2Ref.value);

  // 数据来源
  const pieData = [
    { name: "外购材料", value: totalPCFValue.value },
    { name: "内部工序", value: totalProcessValue.value }
  ];

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} kgCO₂eq ({d}%)"
    },
    legend: {
      orient: "horizontal",
      bottom: "5%"
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"], // 形成环形饼图
        label: {
          show: true,
          position: "outside",
          formatter: "{b}: {c} kgCO₂eq ({d}%)"
        },
        data: pieData,
        emphasis: {
          itemStyle: {
            color: "#6B9DFE"
          }
        }
      }
    ]
  };

  useEcharts(myChart, option);
};
const initChart_Process = () => {
  if (!echarts3Ref.value) return;
  const myChart = echarts.init(echarts3Ref.value);
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "10%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: eachProcessPCF.value.map((item: { name: any }) => item.name),
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: "value",
      name: "kgCO2eq",
      nameLocation: "middle",
      nameGap: 40
    },
    series: [
      {
        type: "bar",
        barWidth: "45px",
        data: eachProcessPCF.value.map((item: { value: any }) => item.value),
        itemStyle: {
          color: "#C5D8FF",
          borderRadius: [12, 12, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: "#6B9DFE"
          }
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c} kgCO2eq"
        }
      }
    ]
  };
  useEcharts(myChart, option);
};
</script>
<style>
.table-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  margin-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.echarts {
  width: 100%;
  height: 400px;
}
.custom-descriptions .el-descriptions__label {
  width: 150px !important;
  font-weight: 500;
}
.custom-descriptions .el-descriptions__content {
  word-break: break-all;
}
</style>
